package it.blog.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.xml.ws.wsaddressing.W3CEndpointReference;


import it.blog.stub.*;


public class AddBlog extends HttpServlet{

	private static final long serialVersionUID = 1L;
		
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		Blog blog = new Blog();
		HttpSession session =  request.getSession();
		AuthBlogPortalService us= new AuthBlogPortalService();
		W3CEndpointReference ref=(W3CEndpointReference)session.getAttribute("ref");
		AuthBlogPortal userAuthenticate=us.getPort(ref, AuthBlogPortal.class);
		
		session.removeAttribute("mess");
		int ownerID = Integer.parseInt(request.getParameter("blogOwner"));
		blog.setBlogTitle(request.getParameter("blogTitle"));
		blog.setBlogOwner(ownerID);
		blog.setBlogCategory(Integer.parseInt(request.getParameter("blogCategory")));
		blog.setCounterBlogView(0);
		blog.setImgURL("");
		
		
		if(userAuthenticate.createBlog(blog)){
			//Redirect alla pagina opportuna dopo aver creato correttamente il blog e aggiornato la url del Blog
			User user =(User) session.getAttribute("user");
			
			user.setBlogURL(""+ user.getUserID() +"");
			session.setAttribute("user", user);

		}else{
			session.setAttribute("mess","creazione blog fallita");
		}
		response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/PortalServlet"));
	}

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		int userID = Integer.parseInt(request.getParameter("userID"));
		request.getSession().setAttribute("userID", userID);

		response.sendRedirect(response.encodeRedirectURL(request.getContextPath()+"/private/addBlog.jsp" ));

	}







}
